package cryptox

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"golang.org/x/crypto/bcrypt"
)

func MD5(bytes []byte) string {
	sum := md5.Sum(bytes)
	return fmt.Sprintf("%x", sum)
}

func MD5s(str string) string {
	return MD5([]byte(str))
}

func Hash(str string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(str), bcrypt.DefaultCost)
}

func HashValidate(plainText string, hashed string) (isOK bool, err error) {
	if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(plainText)); err != nil {
		return false, errors.New("not equal")
	}
	return true, nil
}

var hash = sha256.New()

func MarshalSHA256(s string) string {
	hash.Write([]byte(s))
	return base64.URLEncoding.EncodeToString(hash.Sum(nil))
}
